#!/bin/bash

# 参数：人类或小鼠
Species=$1

# 根据物种选择参考基因组路径
case $Species in
  human|Human)
    RefDir=${REF_DIR_HUMAN:-"/Reference/refdata-gex-GRCh38-2020-A"}
    ;;

  mouse|Mouse)
    RefDir=${REF_DIR_MOUSE:-"/Reference/refdata-gex-mm10-2020-A"}
    ;;

  *)
    echo "Please specify 'human' or 'mouse' as the first argument."
    exit 1
    ;;
esac

# 打印参考基因组路径
echo "Using reference genome: $Species"

# 创建目录
mkdir -p 01.SRA 02.SRAToFastq 03.Exp 04.Report

# 转换 SRA 文件为 FASTQ
# cd 01.SRA
ls ./01.SRA/ | while read ID; do
  parallel-fastq-dump --split-files -s ./01.SRA/$ID --gzip -t 50 -O ./02.SRAToFastq/
done

# 改名
for file in ./02.SRAToFastq/*.fastq.gz; do
  if [[ $file == *"_1.fastq.gz" ]]; then
    mv "$file" "${file/_1.fastq.gz/_S1_L001_I1_001.fastq.gz}"
  elif [[ $file == *"_2.fastq.gz" ]]; then
    mv "$file" "${file/_2.fastq.gz/_S1_L001_R1_001.fastq.gz}"
  elif [[ $file == *"_3.fastq.gz" ]]; then
    mv "$file" "${file/_3.fastq.gz/_S1_L001_R2_001.fastq.gz}"
  fi
done

# 运行 cellranger count
ls ./02.SRAToFastq/*.gz | cut -d _ -f1 | uniq | while read ID; do
  cellranger count \
    --id=$ID \
    --sample=$ID \
    --transcriptome="$RefDir" \
    --fastqs=./02.SRAToFastq \
    --localcores=40 \
    --localmem=300 \
    --nosecondary
done

# 拷贝文件
ls ./02.SRAToFastq/*.gz | cut -d _ -f1 | uniq | while read ID; do
  # 确保路径存在
  cp -r "$ID/outs/filtered_feature_bc_matrix" ./03.Exp/
  mv "./03.Exp/filtered_feature_bc_matrix" "./03.Exp/${ID}"
  cp "$ID/outs/web_summary.html" ./04.Report/
  mv "./04.Report/web_summary.html" "./04.Report/${ID}_web_summary.html"
done


# 整理结果
mkdir CellrangerOutcome
mv 03.Exp 04.Report ./CellrangerOutcome/